//
//  LeftViewController.m
//  QuickCure1
//
//  Created by maoge on 16/10/30.
//  Copyright © 2016年 maoge. All rights reserved.


#import "LeftViewController.h"
#import "DoctorApplyController.h"
#import "SickManagerController.h"
#import "FocusDoctorController.h"
#import "SettingViewController.h"
#import "AboutProductController.h"
#import "SharedViewController.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import <UIImageView+WebCache.h>
//分享给好友
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "Users.h"
#import "EditUserInfoViewController.h"
#import "MapViewController.h"
#import "EditUserInfoModel.h"



@interface LeftViewController ()<UITableViewDelegate,UITableViewDataSource>

/** 没有登录界面 */
@property (nonatomic, strong) UIView *noLoginBGView;

/** 有登录界面 */
@property (nonatomic, strong) UIView *loginBGView;

/** tableView */
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSArray *arrData1;

@property (nonatomic, strong) NSArray *arrData2;

@property (nonatomic, strong) NSArray *viewControllers;

//遮罩
@property (nonatomic, weak) UIView *coverView;


//分享vc
@property (nonatomic, strong) SharedViewController *sharedVc;

//记录用户登录成功后传回来的数据
@property (nonatomic,strong)Users *us;

//头像
@property (nonatomic,weak)UIImageView *iconV;
//姓名
@property (nonatomic,weak)UILabel *nameLabel;


@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configureUI];

    [self setupUI];

    //订阅轻触主界面vc通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeVcTap) name:@"centerVcTap" object:nil];
}



//视图将要出现, 沙盒判断当前是否登陆
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self configureLoginView];
    
}



-(void)configureLoginView{
    
    BOOL isLogin = [MLDefaults boolForKey:kIsUserLoginKey];
    
    self.noLoginBGView.hidden = isLogin;
    
    self.loginBGView.hidden = !isLogin;
    
    self.tableview.hidden = !isLogin;
    
    _isLogin = isLogin;
}

#pragma mark  - Actions
- (void)clickButton:(UIButton *)btn{
    
    //点击'登录'
    if (btn.tag == 101) {
        
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        //登录成功后的block回调
        __weak LeftViewController *selfVC = self;
        loginVC.LogInCompleteBlock = ^(Users *us){
             
            [selfVC configureLoginView];
            selfVC.us = us;
        };
        [self jumpToOtherViewController:loginVC];
        
    }
    //点击'注册'
    else{
        
        RegisterViewController *registerVC = [[RegisterViewController alloc] init];
        registerVC.LogInCompleteBlock = ^(Users *us){
            NSLog(@"传值传的我都晕了%@",us);
            
            [self configureLoginView];
            self.us = us;
        };
        
        [self jumpToOtherViewController:registerVC];
    }
}

#pragma mark  - 配置
-(void)configureUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.hidden = YES;
    
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.arrData1 = @[@"名医通申请",@"病例管理",@"关注医生"];
    
    self.arrData2 = @[@"设置与帮助",@"关于产品",@"分享给好友", @"我的位置"];
 
    self.viewControllers = @[@"DoctorApplyController", @"SickManagerController",
                             @"FocusDoctorController", @"SettingViewController",
                             @"AboutProductController", @"SharedViewController"];
}

#pragma mark  - 设置UI
- (void)setupUI {
    
    //********登录和未登录都已写好，切换点在此，别忘了*************
    
    [self.view addSubview:self.loginBGView];
    
    [self.view addSubview:self.noLoginBGView];
    
    [self.view addSubview:self.tableview];
    
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.loginBGView.mas_bottom);
        make.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_LEFT_WIDTH);
    }];
    
//    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.mas_equalTo(self.noLoginBGView.mas_bottom);
//        make.left.bottom.mas_equalTo(0);
//        make.width.mas_equalTo(SCREEN_LEFT_WIDTH);
//    }];
    
    //取消分割线
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}


#pragma mark  - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 3;
    }
    else {
        
        return 4;  //因为数据少，就直接定死
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.section==0) {
        
        cell.textLabel.text = self.arrData1[indexPath.row];
        
    }else{
        
        cell.textLabel.text = self.arrData2[indexPath.row];
    }
    
    //设置字体
    cell.textLabel.font = MYROUNDFONT(15);
    
    //设置分割线
    UIImageView *separatView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"table_item_bk_with_top_gray_corner"]];
    [cell.contentView addSubview:separatView];
    
    [separatView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(cell.contentView);
        make.height.mas_equalTo(5);
    }];
    
    return cell;
}
#pragma mark  - UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 0.01;
    }
    return 5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    NSInteger row     = indexPath.row;
    
    //1.创建一个空的，下面重新赋值
    UIViewController *newVC = nil;
    
    if (section==0) {
        
        switch (row) {
            case 0:
                
                //2. 赋值
                newVC = (DoctorApplyController *)[[DoctorApplyController alloc] init];
                
                break;
                
            case 1:
                
                newVC = (SickManagerController *)[[SickManagerController alloc] init];
                
                break;
                
            case 2:
                
                newVC = (FocusDoctorController *)[[FocusDoctorController alloc] init];
                
                break;
                
            default:
                break;
        }
        
        //3.都要设置所在控制器title值
        newVC.title = self.arrData1[row];
        
    }else{
        
        switch (row) {
            case 0:
            {
                SettingViewController *set =[SettingViewController new];
                
                set.cancellationBlock =^(){
                    //注销用户
                    [[UserManager sharedManager]cancellationUserInfo];
                    [self configureLoginView];
                };
                newVC = set;
            }
                break;
                
            case 1:
                
                newVC = (AboutProductController *)[[AboutProductController alloc] init];
                break;
                
            case 2: {
                
//                //分享视图
//                SharedViewController *sharedVc = [[SharedViewController alloc] init];
//                
//                [self.view addSubview:sharedVc.view];
//                
//                UITapGestureRecognizer *tapCover = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCover)];
//
//                [sharedVc.coverView addGestureRecognizer:tapCover];
//
//                _coverView = sharedVc.coverView;
                
                
                
                
                //框架分享功能
                //1、创建分享参数
                NSArray* imageArray = @[[UIImage imageNamed:@"banner"]];
                //        （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
                if (imageArray) {
                    
                    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
                    [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                                     images:imageArray
                                                        url:[NSURL URLWithString:@"http://mob.com"]
                                                      title:@"分享标题"
                                                       type:SSDKContentTypeAuto];
                    //2、分享（可以弹出我们的分享菜单和编辑界面）
                    [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                             items:nil
                                       shareParams:shareParams
                               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                                   
                                   switch (state) {
                                       case SSDKResponseStateSuccess:
                                       {
                                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                               message:nil
                                                                                              delegate:nil
                                                                                     cancelButtonTitle:@"确定"
                                                                                     otherButtonTitles:nil];
                                           [alertView show];
                                           break;
                                       }
                                       case SSDKResponseStateFail:
                                       {
                                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                                          delegate:nil
                                                                                 cancelButtonTitle:@"OK"
                                                                                 otherButtonTitles:nil, nil];
                                           [alert show];
                                           break;
                                       }
                                       default:
                                           break;
                                   }
                               }  
                     ];}

                
                
                return;
                
            }
            case 3:
                newVC = (MapViewController *)[[MapViewController alloc] init];
            default:
                break;
        }
        

        newVC.title = self.arrData2[row];
        
    }
    
    //4. 通过centerPanel 跳转
    [self jumpToOtherViewController: newVC];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - tap监听 遮罩移除
- (void)tapCover {
    
    [_coverView.superview removeFromSuperview];
    
}

#pragma mark - 通知监听 轻触homevc移除
- (void)homeVcTap {
    
    [_coverView.superview removeFromSuperview];
    
}


#pragma mark  - Lazy
-(UITableView *)tableview{
    
    if (_tableview == nil) {
        
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        _tableview.dataSource = self;
        _tableview.delegate = self;
        
    }
    return _tableview;
}


-(UIView *)noLoginBGView{
    
    if (_noLoginBGView == nil) {
        _noLoginBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , 120)];
        
        UIImage *backImg = [UIImage imageNamed:@"new_background"];
        UIColor *bc = [UIColor colorWithPatternImage:backImg];
        _noLoginBGView.backgroundColor = bc;
        
        //头像
        UIImageView *iconV = [[UIImageView alloc] init];
        
        iconV.image = [UIImage imageNamed:@"name"];
        [_noLoginBGView addSubview:iconV];
        iconV.bounds = CGRectMake(0, 0, 45, 45);
        iconV.center = CGPointMake(SCREEN_LEFT_WIDTH/2, 50);
        
        
        //登录
        UIButton *leftButton = [[UIButton alloc] init];
        [_noLoginBGView addSubview:leftButton];
        leftButton.tag = 101;
        [leftButton setTitle:@"登录" forState:UIControlStateNormal];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(iconV.mas_bottom).offset(10);
            make.right.mas_equalTo(iconV.mas_centerX).offset(-10);
            make.size.mas_equalTo(CGSizeMake(100, 30));
        }];
        
        //注册
        UIButton *rightButton = [[UIButton alloc] init];
        [_noLoginBGView addSubview:rightButton];
        rightButton.tag = 102;
        [rightButton setTitle:@"注册" forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(iconV.mas_bottom).offset(10);
            make.left.mas_equalTo(iconV.mas_centerX).offset(10);
            make.size.mas_equalTo(CGSizeMake(100, 30));
        }];
        
    }
    
    return _noLoginBGView;
}

-(UIView *)loginBGView{
    
    if (_loginBGView == nil) {
        _loginBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , 120)];
        
        UIImage *backImg = [UIImage imageNamed:@"new_background"];
        UIColor *bc = [UIColor colorWithPatternImage:backImg];
        _loginBGView.backgroundColor = bc;
        
        
        //路径-->用户信息反归档档
//        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInfo.plist"];
//    
//        Users *us = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//        [UserManager sharedManager].userInfo = us;
        [[UserManager sharedManager]getUserInfoFromCache];
        Users *us = [UserManager sharedManager].userInfo;
//        NSLog(@"%@",us);
        //头像
        UIImageView *iconV = [[UIImageView alloc] init];
        self.iconV = iconV;
//        if (us) {
//            [iconV sd_setImageWithURL:[NSURL URLWithString:us.head_photo]];
//        }else{
//            iconV.image = [UIImage imageNamed:@"cangcang"];
//        }
        //给头像添加手势tap
        iconV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickIconV:)];
        [iconV addGestureRecognizer:tap];
        
        iconV.image = [UIImage imageNamed:@"cangcang"];
        [_loginBGView addSubview:iconV];
        iconV.layer.cornerRadius = 35;
        iconV.layer.masksToBounds = YES;
        
        [iconV mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.size.mas_equalTo(CGSizeMake(70, 70));
            make.left.mas_equalTo(20);
            make.top.mas_equalTo(30);
        }];
        
        //昵称
        UILabel *nameLabel = [[UILabel alloc] init];
        self.nameLabel = nameLabel;
        if (us) {
            nameLabel.text = us.true_name;
        }else{
            nameLabel.text = @"小苍苍";
        }
        nameLabel.font = MYROUNDFONT(16);
        [_loginBGView addSubview:nameLabel];
        
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(iconV).offset(5);
            make.left.mas_equalTo(iconV.mas_right).offset(15);
            
        }];
        
        //个人资料
        UILabel *descLabel = [[UILabel alloc] init];
        descLabel.text = @"查看个人资料";
        descLabel.font = MYROUNDFONT(15);
        [_loginBGView addSubview:descLabel];
        [descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.equalTo(iconV).offset(-5);
            make.left.mas_equalTo(iconV.mas_right).offset(15);
        }];
    }
    
    return _loginBGView;
}

//头像的点击监听
- (void)clickIconV:(UITapGestureRecognizer *)tap{
    
    NSLog(@"点击了头像");
    
    EditUserInfoViewController *editVC = [[EditUserInfoViewController alloc]init];
    
    [self jumpToOtherViewController:editVC];
    
}



//存储用户的登录数据
- (void)setUs:(Users *)us{
    _us = us;
    
//    [self.iconV sd_setImageWithURL:[NSURL URLWithString:self.us.head_photo]];
    self.iconV.image = [UIImage imageNamed:@"cangcang"];
    self.nameLabel.text = self.us.true_name;
    //路径-->用户信息归档
    [UserManager sharedManager].userInfo = us;
    
    
#pragma mark - 存储修改用户信息界面的假数据到沙盒中
    EditUserInfoModel *editInfoModel = [[EditUserInfoModel alloc]init];
    
    editInfoModel.province_id = [NSString stringWithFormat:@"%zd",[us.province_id intValue]];
    editInfoModel.city_id = [NSString stringWithFormat:@"%zd",[us.city_id integerValue]];
    editInfoModel.weight = us.weight;
    editInfoModel.height = us.height;
    
    NSString *Path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [Path stringByAppendingPathComponent:@"editUserInfo.plist"];
    
    [NSKeyedArchiver archiveRootObject:editInfoModel toFile:filePath];

}

- (void)dealloc {
    
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"leftViewController被移除了");
}

@end
